# coding:UTF-8
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.conf import settings

from common.utils.utils_log import log
from models import Categories
from common.constant import PAGE_LIMIT

import os
import time
# Create your views here.


def admin_home(request):
    """后台首页"""
    log.info("------------------")
    return render(request, 'mngadmin/list.html', {})


def to_upload(request):
    """去上传文件"""
    log.info("------ to_upload -----")
    return render(request, 'mngadmin/upload.html', {})


def save_single_file(upload_path, file_obj):
    """
    @:description 保存单个文件到服务器
    @:param  upload_path 文件上传存放文件路径名，最终路径：media/传入路径
    @:param  file_obj 待上传文件对象
    """
    # 拆离出文件名和文件格式后缀
    original_name, file_extension = os.path.splitext(file_obj.name)
    # 拼接新的文件名
    filename = "%s_%s%s" % (original_name, time.time(), file_extension)
    # 拼接文件上传目录
    path = "%s%s" % (settings.MEDIA_ROOT, upload_path)
    # 如果目录不存在，创建此目录
    if not os.path.exists(path):
        os.makedirs(path)
    # 拼接文件上传存放文件路径
    upload_path = "%s%s" % (path, filename)
    if not os.path.isfile:
        raise Exception("上传失败，不是一个文件!")
    # 上传文件操作
    destination = open(upload_path, 'wb+')
    for chunk in file_obj.chunks():
        destination.write(chunk)
    destination.close()
    return upload_path


def download_file_util(file_path, file_name=None):
    """
    @:description 下载文件
    @:param  file_path 待下载文件路径
    @:param  file_name 下载文件名
    """
    # 根据文件路径获取待下载文件流
    def file_iterator(down_file, chunk_size=1024):
        content = open(down_file, 'rb').read()
        return content
    # 设置响应头
    if os.path.exists(file_path):
        if os.path.isfile(file_path):
            # filename, extension = os.path.splitext(file_path)
            filename = os.path.basename(file_path)
            # 若未指定下载文件名，则已文件本身名称为准
            if not file_name:
                file_name = filename
            response = HttpResponse(file_iterator(file_path))
            response['Content_type'] = "application/octet-stream"
            response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name.encode('utf-8'))
        else:
            response = HttpResponse("下载失败,不是一个文件!", content_type="text/plain;charset=utf-8")
    else:
        response = HttpResponse("文件不存在,下载失败!", content_type="text/plain;charset=utf-8")
    return response


def upload_file(request):
    """上传文件"""
    try:
        file_list = request.FILES
        if file_list:
            file_obj = file_list.get("chat_file")
            # 上传文件大小验证
            if file_obj.size > 1024 * 1024 * 10:
                raise Exception('文件过大,大小不能超过10M')
            else:
                # 调用上传文件方法，返回文件上传路径
                path = save_single_file("/chat_file/", file_obj)
                if path:
                    result = {
                        'status': 1,
                        'file_path': path,
                        'msg': '上传成功'
                    }
        else:
            raise Exception("文件上传失败，请稍后重试!")
    except Exception, e:
        log.exception("upload_file error:%s" % e)
        result = {
            'status': 0,
            'msg': str(e)
        }
    return JsonResponse(result)


def download_file(request):
    """下载文件"""
    file_path = request.GET.get("file_path")
    return download_file_util(file_path)


def get_all_mongo(request):
    """查询所有"""
    data_list = []
    cate_list = []
    data_set = []
    try:
        offset = request.GET.get('offset', 0)
        start = int(offset)
        end = start+PAGE_LIMIT
        #
        data_set = Categories.objects.all()
        cate_list = data_set[start:end]
        for item in cate_list:
           cate_item = {
               'name': item.name,
               'artnum': item.artnum,
               'date': item.date.strftime('%Y-%m-%d %H:%M:%S')
           }
           data_list.append(cate_item)
    except Exception, e:
        log.error("get_all_mongo raise, Error:%s" % e)
    result = {
        'total': len(data_set),
        'rows': data_list
    }
    return JsonResponse(result, safe=False)

def save_all_mongo():
    """查询所有"""
    ca = Categories(name='Linux')
    ca.save()
